/*
* $Id: TableItem.cpp 12 2010-01-08 09:47:33Z volok-aleksej@yandex.ru $
*
* Copyright 2009 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include "TableStructs.h"
#include "TableItem.h"

CItemTable::CItemTable(COLORREF color)
: m_pos(0, 0), m_colorItem(color){}
CItemTable::~CItemTable(){}

void CItemTable::Paint(CDC* dc){
	CBrush brush;
	brush.CreateSolidBrush(m_colorItem);
	dc->FillRect(CRect(m_pos, m_size), &brush);
	CPen pen;
	pen.CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
	HGDIOBJ penOld = dc->SelectObject(pen);
	dc->MoveTo(m_pos.x, m_pos.y);
	dc->LineTo(m_pos.x + m_size.cx, m_pos.y);
	dc->LineTo(m_pos.x + m_size.cx, m_pos.y + m_size.cy);
	dc->LineTo(m_pos.x, m_pos.y + m_size.cy);
	dc->LineTo(m_pos.x, m_pos.y);
	dc->SelectObject(penOld);
	pen.DeleteObject();
	brush.DeleteObject();
	CFont* pFont = CCommonFunction::GetFont(_T("Arial"), sizeFont, TRUE, FALSE);
	HGDIOBJ fontOld = dc->SelectObject(pFont);
	dc->SetBkMode(TRANSPARENT);
	tableItem *item = dynamic_cast<tableItem*>(this);
	dc->DrawText(item->m_strValue.c_str(), CRect(m_pos, m_size), DT_CENTER | DT_WORDBREAK);
	dc->SelectObject(fontOld);
	pFont->DeleteObject();
	delete pFont;
}
CSize CItemTable::GetSize(){
	return m_size;
}

CSize CItemTable::GetDefaultSize(int cx){
	CSize size(0, 0);
	HDC dc = GetDC(GetDesktopWindow());
	tableItem *item = dynamic_cast<tableItem*>(this);
	std::vector<std::tstring> aString = CStringFunction::GetStringArray(item->m_strValue, _T("\n"));
	CFont* pFont = CCommonFunction::GetFont(_T("Arial"), sizeFont, TRUE, FALSE);
	HGDIOBJ font_object = SelectObject(dc, pFont->m_hObject);
	if(cx != 0){
		size.cx = cx;
		for(std::vector<std::tstring>::iterator it = aString.begin(); it != aString.end(); it++){
			std::vector<std::tstring> aTemp = CStringFunction::GetStringArray(*it, _T(" "));
			int szCx = 0;
			for(std::vector<std::tstring>::iterator it = aTemp.begin(); it != aTemp.end(); it++){
				CSize size_temp;
				GetTextExtentPoint32(dc, it->c_str(), (int)it->size(), &size_temp);
				if(szCx + size_temp.cx > cx){
					szCx = 0;
					size.cy += sizeFont + 5;
				}
				else
					szCx += sizeFont + size_temp.cx;
			}
			size.cy += sizeFont + 5;
		}
	}else{
		for(std::vector<std::tstring>::iterator it = aString.begin(); it != aString.end(); it++){
			CSize size_temp;
			GetTextExtentPoint32(dc, it->c_str(), (int)it->size(), &size_temp);
			size.cy += sizeFont + 5;
			if(size_temp.cx > size.cx)
				size.cx = (int)size_temp.cx;
		}
		size.cx += 10;
	}
	SelectObject(dc, font_object);
	pFont->DeleteObject();
	delete pFont;
	DeleteDC(dc);
	return size;
}

CPoint CItemTable::GetPos(){
	return m_pos;
}

void CItemTable::SetColor(COLORREF color){
	m_colorItem = color;
}